package com.mitake.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;

import com.mitake.parse.Day5;
import com.mitake.parse.Day5;
import com.mitake.parse.Day5.Day5Item;
import com.mitake.parse.Day5.Day5Item;
import com.mitake.task.day5.Day5CompareProcess;
import com.mitake.task.day5.Day5CompareTask;
import com.mitake.utils.ExcelUtil;
import com.mitake.utils.Util;
import com.mitake.task.day5.Day5CompareProcess;

public class Day5MonitorActionServlet extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public Day5MonitorActionServlet() {
		super();
	}
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType(Util.CONTENT_TYPE);
		request.setCharacterEncoding(response.getCharacterEncoding());
		String event = request.getParameter("event");
		String src = request.getParameter("src");
		String data = "";
		Day5CompareTask day5CompareTask =Day5CompareTask.getInstance();
		if(event.equals("s")){
			ServletContext context = getServletContext();
			String rootPath = context.getRealPath("");
			/**
			 * 取得询问报告间隔时间
			 */
			day5CompareTask.setRunInterval(Util.getRunInterval(rootPath));
			/**
			 * 取得商品
			 */
			day5CompareTask.setStockList(Util.getStock(rootPath));
			/**
			 * 取得各机房IP
			 */
			day5CompareTask.start(Util.getHost(rootPath));
			data = "{\"code\":\"00000\",\"message\":\"程序启动中\"}";
	        PrintWriter out = response.getWriter();
	        out.println(data);
		}
		else if(event.equals("e"))
		{
			day5CompareTask.stop();
			
			data = "{\"code\":\"00000\",\"message\":\"程序停止中\"}";
	        PrintWriter out = response.getWriter();
	        out.println(data);
		}
		else if(event.equals("g")){
			String[][] status = day5CompareTask.getAllSocketStatus();
			StringBuilder t = new StringBuilder();
			if(status != null)
			{
				t.append("[");
				
				for(int i = 0 ; i < status.length ; i++)
				{
					t.append("{");
					t.append("\"ip\":\"").append(status[i][0]).append("\",");
					t.append("\"status\":\"").append(status[i][1]).append("\"");
					t.append("},");
				}
				
				t.setLength(t.length() - 1);
				t.append("]");
			}
			String[] count = day5CompareTask.getTelegramCount();
			StringBuilder tmp = new StringBuilder();
			tmp.append("{");
			tmp.append("\"code\":\"00000\",");
			tmp.append("\"message\":\"ok\",");
			tmp.append("\"running\":");
			tmp.append((day5CompareTask.isRunning() ? "\"true\"" : "\"false\"")).append(",");
			tmp.append("\"w\":\"");
			tmp.append(count[0]).append("\",");
			tmp.append("\"r\":\"");
			tmp.append(count[1]).append("\",");
			tmp.append("\"host\":");
			tmp.append(t.length() > 0 ? t : "\"\"").append(",");
			Day5[] day5s = Day5CompareProcess.data;
			if(day5s != null){
				int index = Integer.parseInt(src);
					int sendCount = 0;
					tmp.append("\"push\":[");
					
					Day5 flagDay5 =day5s[0];
					for(Map.Entry<String, Day5Item> entry : flagDay5.day5Map.entrySet()){
						sendCount++;
						Day5Item flagDay5Item = entry.getValue();
						if(flagDay5Item.lastPrice.equals("@") || flagDay5Item.volume.equals("@")){
							String key = entry.getKey();
							tmp.append("{\"").append(key).append("\":");
							tmp.append("[");
							
							
							for(int i = 1; i < day5s.length; i++){
								if(i != 1){
									tmp.append(",");
								}
								Day5 day5 = day5s[i];
								Day5Item day5Item = day5.day5Map.get(key);
								tmp.append("{");
								tmp.append("\"host\":").append("\"").append(day5.host).append("\",");
								tmp.append("\"ip\":").append("\"").append(day5.ip).append("\",");
								tmp.append("\"datetime\":").append("\"").append(key).append("\",");
								tmp.append("\"lastPrice\":").append("\"").append(day5Item.lastPrice).append("\",");
								tmp.append("\"volume\":").append("\"").append(day5Item.volume).append("\",");
								tmp.append("\"volume_flag\":").append("\"").append(flagDay5Item.volume.equals("@")?1:0).append("\",");
								tmp.append("\"lastPrice_flag\":").append("\"").append(flagDay5Item.lastPrice.equals("@")?1:0).append("\"");
								tmp.append("}");
							}
							
							
							tmp.append("]");
							tmp.append("},");
						}
					}
					
					if(sendCount > 0){
						String strtmp = tmp.toString();
						tmp.setLength(0);
						tmp.append(strtmp.substring(0, strtmp.length()-1));						
					}
					
					tmp.append("],");
					
					tmp.append("\"index\":").append("\"").append(index + sendCount).append("\"");
			}else{
				tmp.append("\"push\":\"\"");
			}
			tmp.append("}");
			data = tmp.toString();
	        PrintWriter out = response.getWriter();
	        out.println(data);
		}else if(event.equals("download")){
			response.setCharacterEncoding("utf-8");
			Day5[] day5s = Day5CompareProcess.data;
			Day5 flagDay5 = day5s[0];
			StringBuilder tmp = new StringBuilder();
			tmp.append("[");
			for(Map.Entry<String, Day5Item> entry : flagDay5.day5Map.entrySet()){
					String key = entry.getKey();
					Day5Item flagDay5Item = entry.getValue();  
					tmp.append("{\"").append(key).append("\":");  //[{date1:[{},{}]},{date1:[{},{}]}]
					tmp.append("[");
					for(int i = 1; i < day5s.length; i++){
						if(i != 1 ){
							tmp.append(",");
						}
						Day5 day5 = day5s[i];
						Day5Item day5Item = day5.day5Map.get(key);
						tmp.append("{");
						tmp.append("\"host\":").append("\"").append(day5.host).append("\",");
						tmp.append("\"ip\":").append("\"").append(day5.ip).append("\",");
						tmp.append("\"datetime\":").append("\"").append(key).append("\",");
						tmp.append("\"lastPrice\":").append("\"").append(day5Item.lastPrice).append("\",");
						tmp.append("\"volume\":").append("\"").append(day5Item.volume).append("\",");
						tmp.append("\"volume_flag\":").append("\"").append(flagDay5Item.volume.equals("@")?1:0).append("\",");
						tmp.append("\"lastPrice_flag\":").append("\"").append(flagDay5Item.lastPrice.equals("@")?1:0).append("\"");
						tmp.append("}");
					}
					tmp.append("]");
					tmp.append("},");
			}
			//去掉最后一个,
			String strtmp = tmp.toString();
			tmp.setLength(0);
			tmp.append(strtmp.substring(0, strtmp.length()-1));
			tmp.append("]");
			 
			JSONArray jArray = new JSONArray(tmp.toString());
			String path = ExcelUtil.processExcelDay5(jArray,request.getServletContext());
			response.setHeader("content-disposition", "attachment;filename=Day5Line"+System.currentTimeMillis()+".xls");
			InputStream in = new FileInputStream(path);
			int len = 0;
			byte[] buffer = new byte[1024];
	         //6.通过response对象获取OutputStream流
	         OutputStream out = response.getOutputStream();
	         //7.将FileInputStream流写入到buffer缓冲区
		      while ((len = in.read(buffer)) > 0) {
		      //8.使用OutputStream将缓冲区的数据输出到客户端浏览器
		          out.write(buffer,0,len);
		      }
		      in.close();
		}

	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}

}
